﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using PersonaLibrary.Data;
using PersonaLibrary.Search;
using PersonaLibrary.View.NotesView;

namespace PersonaLibrary.ViewModel.NoteViewModel
{
	internal class ConcateNotesViewModel : EditableItemViewModel<Note, ConcateNotesToNew>
	{
		private readonly List<NoteBool> _notes;
		private readonly LinqToDbDataContext _context;

		private RelayCommand _showEmployeesCommand;

		public RelayCommand ShowEmployeesCommand
		{
			get
			{
				if(_showEmployeesCommand == null)
					_showEmployeesCommand = new RelayCommand(x => ShowEmployees(), x => _notes.Any(note => note.IsSelected));
				return _showEmployeesCommand;
			}
		}

		public List<NoteBool> Notes
		{
			get { return _notes; }
		}

		public ConcateNotesViewModel()
		{
			_context = new LinqToDbDataContext();
			_notes = _context.Notes.Select(x => new NoteBool
			                                    	{
			                                    		Note = x, 
														Employees = new List<string>(x.EmployeeNoteLinks.Select(link => link.Employee.ToString()))
			                                    	}).ToList();
		}

		public void ShowEmployees()
		{
			CurrentApplication.Filter = new Filter("EmployeeWithNotes", typeof (Employee))
			                            	{
												DisplayName = "Сотрудники в заметках",
			                            		FuncFilter =
			                            			x =>
			                            			((Employee) x).EmployeeNoteLinks.Any(note => _notes.Any(pNote => pNote.IsSelected && pNote.Note.Id == note.NoteId))
			                            	};
		}

		public override bool CanCommit()
		{
			return _notes.Any(note => note.IsSelected);
		}

		public override void Commit()
		{
			NewNote newNote = new NewNote();
			if (newNote.ShowDialog().GetValueOrDefault(false))
			{
				if(_notes.Any(x => x.Note.Name == newNote.NoteName))
				{
					MessageBox.Show("Примечание {0} уже существует, пожалуйста укажите другое имя");
				}
				else
				{
					Note note = new Note {Name = newNote.NoteName};

					_context.Notes.InsertOnSubmit(note);
					_context.SubmitChanges();

					foreach (var noteBool in _notes.Where(x => x.IsSelected))
					{
						foreach (var employee in noteBool.Note.EmployeeNoteLinks)
						{
							EmployeeNoteLink link = new EmployeeNoteLink {NoteId = note.Id, EmployeeId = employee.EmployeeId};
							_context.EmployeeNoteLinks.InsertOnSubmit(link);
						}
					}

					_context.SubmitChanges();

					base.Commit();
				}
			}
		}

		public class NoteBool
		{
			public Note Note { set; get; }

			public bool IsSelected { set; get; }

			public List<string> Employees { set; get; }
		}
	}
}
